package com.wngbms.netty.seatdemo.service;

import com.wngbms.netty.seatdemo.comm.*;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatInMessage;
import com.wngbms.netty.seatdemo.message.SeatOutMessage;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class EchoHandler implements SeatTypeHandler {
    public static final CmdType CMD_TYPE = CmdType.ECHO;

    @Override
    public void handleInbound(SeatInMessage seatInMessage) {

        for (int i = 0; i < 500; i++) {
            byte[] body = seatInMessage.getBody();
            String s = new String(body, StandardCharsets.UTF_8);
            log.info("echo:{}", s);
            BaseHeader baseHeader = BaseHeader.build(MagicVersion.V1,
                    CmdType.ECHO, BodyType.TEXT,
                    EncryptionType.NON, ReqOrResp.RESP,
                    body.length);

            Channel channel = seatInMessage.getChannelHandlerContext().channel();

            SeatOutMessage seatOutMessage = new SeatOutMessage();
            seatOutMessage.setBaseHeader(baseHeader);
            seatOutMessage.setBody(body);

            if (channel.isActive() && channel.isWritable()) {
                channel.writeAndFlush(seatOutMessage);
            } else {
                log.info("channel状态不可用:a,{} b,{}", channel.isActive(), channel.isWritable());
            }
        }

    }
}
